package com.atguigu.flink.chapter11;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Schema;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/20 10:54
 */
public class Flink03_Table_Connector_File {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
    
        Schema schema = new Schema()
            .field("id", DataTypes.STRING())
            .field("ts", DataTypes.BIGINT())
            .field("vc", DataTypes.INT());
        
        tenv
            .connect(new FileSystem().path("input/sensor.txt"))
            .withFormat(new Csv().fieldDelimiter(',').lineDelimiter("\n"))
            .withSchema(schema)
            .createTemporaryTable("sensor");
    
        Table table = tenv.from("sensor");
        
        //table.execute().print(); // 直接打印, 一般只用于测试
        
        // 建立一个动态表与sink关联, 然后把数据写入到动态表,则自动到了sink的位置
        tenv
            .connect(new FileSystem().path("input/abc.txt"))
            .withFormat(new Csv())
            .withSchema(schema)
            .createTemporaryTable("s1");
    
        Table result = table.where($("id").isEqual("sensor_1"))
            .select("*");
        result.executeInsert("s1");
    
    }
}
